<?php
include 'includes/header.php';
require_once 'config/database.php';

if (!isset($_GET['id'])) {
    redirect('cars.php');
}

$database = new Database();
$db = $database->getConnection();

// Get car details with brand and model
$query = "SELECT c.*, b.name as brand_name, m.name as model_name 
          FROM cars c 
          LEFT JOIN brands b ON c.brand_id = b.id 
          LEFT JOIN models m ON c.model_id = m.id 
          WHERE c.id = ?";
$stmt = $db->prepare($query);
$stmt->execute([$_GET['id']]);
$car = $stmt->fetch();

if (!$car) {
    redirect('cars.php');
}

$is_in_favorites = false;
if (isset($_SESSION['user_id'])) {
    $fav_check_query = "SELECT id FROM favorites WHERE user_id = ? AND car_id = ?";
    $fav_check_stmt = $db->prepare($fav_check_query);
    $fav_check_stmt->execute([$_SESSION['user_id'], $car['id']]);
    $is_in_favorites = $fav_check_stmt->rowCount() > 0;
}

// Get additional images
$images_query = "SELECT * FROM car_images WHERE car_id = ?";
$images_stmt = $db->prepare($images_query);
$images_stmt->execute([$_GET['id']]);
$additional_images = $images_stmt->fetchAll();

// Get similar cars
$similar_query = "SELECT c.*, b.name as brand_name, m.name as model_name 
                 FROM cars c 
                 LEFT JOIN brands b ON c.brand_id = b.id 
                 LEFT JOIN models m ON c.model_id = m.id 
                 WHERE c.brand_id = ? AND c.id != ? AND c.status = 'Available'
                 LIMIT 3";
$similar_stmt = $db->prepare($similar_query);
$similar_stmt->execute([$car['brand_id'], $car['id']]);
$similar_cars = $similar_stmt->fetchAll();

// All images array for gallery
$all_images = array_merge(
    [['image_path' => $car['main_image']]], 
    $additional_images
);

// Get user details if logged in
$user_details = null;
if (isset($_SESSION['user_id'])) {
    $user_query = "SELECT first_name, last_name, email, phone FROM users WHERE id = ?";
    $user_stmt = $db->prepare($user_query);
    $user_stmt->execute([$_SESSION['user_id']]);
    $user_details = $user_stmt->fetch();
}

?>
<!-- Basic SEO -->
<title><?php echo htmlspecialchars($car['title'] . ' - ' . $car['brand_name'] . ' ' . $car['model_name']); ?></title>
<meta name="description" content="<?php echo htmlspecialchars(substr(strip_tags($car['description']), 0, 160)); ?>">
<meta name="keywords" content="<?php echo htmlspecialchars($car['brand_name'] . ', ' . $car['model_name'] . ', ' . $car['year'] . ', ' . $car['condition_type'] . ' car, ' . $car['transmission'] . ', ' . $car['fuel_type']); ?>">

<!-- Open Graph / Facebook -->
<meta property="og:type" content="product">
<meta property="og:url" content="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>">
<meta property="og:title" content="<?php echo htmlspecialchars($car['title'] . ' - ' . $car['brand_name'] . ' ' . $car['model_name']); ?>">
<meta property="og:description" content="<?php echo htmlspecialchars(substr(strip_tags($car['description']), 0, 160)); ?>">
<meta property="og:image" content="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . '/uploads/cars/' . $car['main_image']; ?>">
<meta property="og:price:amount" content="<?php echo $car['price']; ?>">
<meta property="og:price:currency" content="USD">

<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="<?php echo htmlspecialchars($car['title'] . ' - ' . $car['brand_name'] . ' ' . $car['model_name']); ?>">
<meta name="twitter:description" content="<?php echo htmlspecialchars(substr(strip_tags($car['description']), 0, 160)); ?>">
<meta name="twitter:image" content="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . '/uploads/cars/' . $car['main_image']; ?>">

<!-- Additional SEO -->
<link rel="canonical" href="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>">
<meta name="robots" content="index, follow">
<meta property="product:price:amount" content="<?php echo $car['price']; ?>">
<meta property="product:price:currency" content="USD">
<meta property="product:availability" content="<?php echo $car['status'] === 'Available' ? 'in stock' : 'out of stock'; ?>">
<meta property="product:condition" content="<?php echo strtolower($car['condition_type']); ?>">

<!-- JSON-LD structured data -->
<script type="application/ld+json">
{
    "@context": "https://schema.org/",
    "@type": "Vehicle",
    "name": "<?php echo htmlspecialchars($car['title']); ?>",
    "brand": {
        "@type": "Brand",
        "name": "<?php echo htmlspecialchars($car['brand_name']); ?>"
    },
    "model": "<?php echo htmlspecialchars($car['model_name']); ?>",
    "modelDate": "<?php echo $car['year']; ?>",
    "vehicleConfiguration": "<?php echo htmlspecialchars($car['transmission'] . ' ' . $car['fuel_type']); ?>",
    "mileageFromOdometer": {
        "@type": "QuantitativeValue",
        "value": <?php echo $car['mileage']; ?>,
        "unitCode": "KMT"
    },
    "offers": {
        "@type": "Offer",
        "priceCurrency": "USD",
        "price": <?php echo $car['price']; ?>,
        "availability": "<?php echo $car['status'] === 'Available' ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock'; ?>",
        "itemCondition": "https://schema.org/<?php echo ucfirst($car['condition_type']); ?>Condition"
    },
    "description": "<?php echo htmlspecialchars(substr(strip_tags($car['description']), 0, 160)); ?>",
    "image": "<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . '/uploads/cars/' . $car['main_image']; ?>"
}
</script>
<?php

?>

<div class="container py-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="index.php">Home</a></li>
            <li class="breadcrumb-item"><a href="cars.php">Cars</a></li>
            <li class="breadcrumb-item active"><?php echo htmlspecialchars($car['title']); ?></li>
        </ol>
    </nav>

    <div class="row">
        <!-- Image Gallery -->
        <div class="col-lg-8 mb-4">
            <div class="card shadow-sm">
                <div class="swiper mainSwiper mb-3">
                    <div class="swiper-wrapper">
                        <?php foreach ($all_images as $image): ?>
                            <div class="swiper-slide">
                                <img src="<?php echo htmlspecialchars($image['image_path']); ?>" 
                                     class="img-fluid" 
                                     alt="<?php echo htmlspecialchars($car['title']); ?>"
                                     style="height: 400px; width: 100%; object-fit: cover;">
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="swiper-button-next"></div>
                    <div class="swiper-button-prev"></div>
                </div>

                <div class="swiper thumbSwiper px-2">
                    <div class="swiper-wrapper">
                        <?php foreach ($all_images as $image): ?>
                            <div class="swiper-slide">
                                <img src="<?php echo htmlspecialchars($image['image_path']); ?>" 
                                     class="img-fluid" 
                                     style="height: 80px; width: 100%; object-fit: cover; cursor: pointer;">
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Car Details -->
        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h2 class="card-title mb-3"><?php echo htmlspecialchars($car['title']); ?></h2>
                    <div class="price-badge mb-4">
                        <h3 class="text-primary mb-0">$<?php echo number_format($car['price']); ?></h3>
                    </div>

                    <div class="key-features mb-4">
                        <div class="row g-2">
                            <div class="col-6">
                                <div class="feature-item">
                                    <i class="fas fa-calendar-alt text-primary"></i>
                                    <span>Year: <?php echo $car['year']; ?></span>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="feature-item">
                                    <i class="fas fa-road text-primary"></i>
                                    <span>Mileage: <?php echo number_format($car['mileage']); ?> km</span>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="feature-item">
                                    <i class="fas fa-gas-pump text-primary"></i>
                                    <span>Fuel: <?php echo $car['fuel_type']; ?></span>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="feature-item">
                                    <i class="fas fa-cog text-primary"></i>
                                    <span>Transmission: <?php echo $car['transmission']; ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['user_id'])): ?>
                        <div class="action-buttons">
                            <a href="https://wa.me/1234567890?text=<?php echo urlencode('Hi, I\'m interested in ' . $car['title'] . ' listed at ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" 
                                class="btn btn-success w-100 mb-2" target="_blank">
                                <i class="fab fa-whatsapp me-2"></i>Chat on WhatsApp
                            </a>                           
                            <button class="btn btn-primary w-100 mb-2" data-bs-toggle="modal" data-bs-target="#inquiryModal">
                                <i class="fas fa-envelope me-2"></i>Send Inquiry
                            </button>
                            <button class="btn btn-outline-primary w-100 mb-2" data-bs-toggle="modal" data-bs-target="#testDriveModal">
                                <i class="fas fa-car me-2"></i>Schedule Test Drive
                            </button>
                            <button class="btn btn-outline-danger w-100 toggle-favorite" data-car-id="<?php echo $car['id']; ?>">
                                <i class="<?php echo $is_in_favorites ? 'fas' : 'far'; ?> fa-heart me-2"></i>
                                <?php echo $is_in_favorites ? 'Remove from Favorites' : 'Add to Favorites'; ?>
                            </button>
                            <a href="compare.php?add=<?php echo $car['id']; ?>" class="btn btn-outline-primary w-100 mb-2">
                                <i class="fas fa-balance-scale me-2"></i>Add to Compare
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info">
                            <a href="login.php">Login</a> to schedule a test drive or send an inquiry and  add to favorites
                        </div>
                        <div class="action-buttons">
                            <a href="https://wa.me/1234567890?text=<?php echo urlencode('Hi, I\'m interested in ' . $car['title'] . ' listed at ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" 
                                class="btn btn-success w-100 mb-2" target="_blank">
                                <i class="fab fa-whatsapp me-2"></i>Chat on WhatsApp
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Car Description -->
        <div class="col-12 mt-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <ul class="nav nav-tabs" id="carDetailsTabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="description-tab" data-bs-toggle="tab" href="#description">
                                Description
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="features-tab" data-bs-toggle="tab" href="#features">
                                Features
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="specifications-tab" data-bs-toggle="tab" href="#specifications">
                                Specifications
                            </a>
                        </li>
                    </ul>

                    <div class="tab-content pt-4" id="carDetailsContent">
                        <div class="tab-pane fade show active" id="description">
                            <?php echo nl2br(htmlspecialchars($car['description'])); ?>
                        </div>
                        <div class="tab-pane fade" id="features">
                            <div class="row">
                                <?php 
                                $features = explode("\n", $car['features']);
                                foreach ($features as $feature): 
                                ?>
                                    <div class="col-md-4 mb-2">
                                        <div class="feature-item">
                                            <i class="fas fa-check text-success me-2"></i>
                                            <?php echo htmlspecialchars(trim($feature)); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="tab-pane fade" id="specifications">
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table">
                                        <tr>
                                            <th>Brand:</th>
                                            <td><?php echo htmlspecialchars($car['brand_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Model:</th>
                                            <td><?php echo htmlspecialchars($car['model_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Year:</th>
                                            <td><?php echo $car['year']; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Body Type:</th>
                                            <td><?php echo $car['body_type']; ?></td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table">
                                        <tr>
                                            <th>Fuel Type:</th>
                                            <td><?php echo $car['fuel_type']; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Transmission:</th>
                                            <td><?php echo $car['transmission']; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Drive Terrain:</th>
                                            <td><?php echo $car['drive_terrain']; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Condition:</th>
                                            <td><?php echo $car['condition_type']; ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Similar Cars -->
        <?php if ($similar_cars): ?>
        <div class="col-12 mt-4">
            <h3 class="mb-4">Similar Cars</h3>
            <div class="row row-cols-1 row-cols-md-3 g-4">
                <?php foreach ($similar_cars as $similar_car): ?>
                    <div class="col">
                        <div class="car-card h-100">
                            <img src="<?php echo htmlspecialchars($similar_car['main_image']); ?>" 
                                 class="card-img-top" 
                                 alt="<?php echo htmlspecialchars($similar_car['title']); ?>"
                                 style="height: 200px; object-fit: cover;">
                            <div class="card-body pt-3 mt-2">
                                <h5 class="card-title"><?php echo htmlspecialchars($similar_car['title']); ?></h5>
                                <p class="card-text">$<?php echo number_format($similar_car['price']); ?></p>
                                <a href="car-details.php?id=<?php echo $similar_car['id']; ?>" 
                                   class="btn btn-outline-primary">View Details</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add this right after the opening <body> tag or before any modals -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="toastNotification" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <i class="fas fa-info-circle me-2"></i>
            <strong class="me-auto" id="toastTitle">Notification</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>
</div>

<!-- Modify the Inquiry Modal -->
<div class="modal fade" id="inquiryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Send Inquiry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="inquiryForm">
                <div class="modal-body">
                    <input type="hidden" name="car_id" value="<?php echo $car['id']; ?>">
                    <?php if (isset($_SESSION['user_id'])): ?>
                        <!-- Show user's info for reference -->
                        <div class="mb-3">
                            <div class="alert alert-info">
                                <strong>Sending inquiry as:</strong><br>
                                Name: <?php echo htmlspecialchars($user_details['first_name'] . ' ' . $user_details['last_name']); ?><br>
                                Email: <?php echo htmlspecialchars($user_details['email']); ?><br>
                                Phone: <?php echo htmlspecialchars($user_details['phone']); ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label">Your Message</label>
                        <textarea class="form-control" name="message" rows="4" required 
                                  placeholder="Please write your message or any specific questions about the <?php echo htmlspecialchars($car['brand_name'] . ' ' . $car['model_name']); ?> here..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Send Inquiry</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Test Drive Modal -->
<div class="modal fade" id="testDriveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Schedule Test Drive</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="submit_test_drive.php" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="car_id" value="<?php echo $car['id']; ?>">
                    <div class="mb-3">
                        <label class="form-label">Preferred Date</label>
                        <input type="date" class="form-control" name="preferred_date" required
                               min="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Preferred Time</label>
                        <input type="time" class="form-control" name="preferred_time" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Schedule</button>
                </div>
            </form>
        </div>
    </div>
</div>

<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>

<style>
.feature-item {
    padding: 10px;
    background: #f8f9fa;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.feature-item i {
    width: 20px;
}

.nav-tabs .nav-link {
    color: #666;
    border: none;
    border-bottom: 2px solid transparent;
    padding: 10px 20px;
}

.nav-tabs .nav-link.active {
    color: var(--bs-primary);
    border-bottom: 2px solid var(--bs-primary);
}

.swiper {
    width: 100%;
    height: 100%;
}

.mainSwiper {
    height: 400px;
    margin-bottom: 10px;
}

.thumbSwiper {
    height: 100px;
    box-sizing: border-box;
    padding: 10px 0;
}

.thumbSwiper .swiper-slide {
    opacity: 0.4;
    cursor: pointer;
}

.thumbSwiper .swiper-slide-thumb-active {
    opacity: 1;
}

.car-card {
    transition: transform 0.3s ease;
}

.car-card:hover {
    transform: translateY(-5px);
}

/* Animations */
.card {
    animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.toast {
    min-width: 300px;
}

.toast.bg-success,
.toast.bg-danger {
    color: white;
}

.toast .btn-close {
    filter: brightness(0) invert(1);
}
</style>

<script>
var thumbSwiper = new Swiper(".thumbSwiper", {
    spaceBetween: 10,
    slidesPerView: 4,
    freeMode: true,
    watchSlidesProgress: true,
});

var mainSwiper = new Swiper(".mainSwiper", {
    spaceBetween: 10,
    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
    },
    thumbs: {
        swiper: thumbSwiper,
    },
});

// Favorite functionality
document.querySelector('.toggle-favorite')?.addEventListener('click', function() {
    const carId = this.dataset.carId;
    const icon = this.querySelector('i');
    const button = this;
    
    fetch('ajax/toggle_favorite.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'car_id=' + carId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (icon.classList.contains('far')) {
                icon.classList.remove('far');
                icon.classList.add('fas');
                button.innerHTML = `<i class="fas fa-heart me-2"></i>Remove from Favorites`;
            } else {
                icon.classList.remove('fas');
                icon.classList.add('far');
                button.innerHTML = `<i class="far fa-heart me-2"></i>Add to Favorites`;
            }
        } else {
            alert(data.message || 'Error updating favorite status');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating favorite status');
    });
});

// Function to show toast notification
function showToast(message, isSuccess = true) {
    const toast = document.getElementById('toastNotification');
    const toastTitle = document.getElementById('toastTitle');
    const toastMessage = document.getElementById('toastMessage');
    const bsToast = new bootstrap.Toast(toast);
    
    toast.classList.remove('bg-success', 'bg-danger', 'text-white');
    if (isSuccess) {
        toast.classList.add('bg-success', 'text-white');
        toastTitle.textContent = 'Success';
    } else {
        toast.classList.add('bg-danger', 'text-white');
        toastTitle.textContent = 'Error';
    }
    
    toastMessage.textContent = message;
    bsToast.show();
}

// Check for session messages on page load
<?php if (isset($_SESSION['success'])): ?>
    showToast("<?php echo addslashes($_SESSION['success']); ?>", true);
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
    showToast("<?php echo addslashes($_SESSION['error']); ?>", false);
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

// Inquiry form submission
document.getElementById('inquiryForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitButton = this.querySelector('button[type="submit"]');
    submitButton.disabled = true;
    
    fetch('submit_inquiry.php', {
        method: 'POST',
        body: new URLSearchParams(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(data.message, true);
            this.reset();
            const modal = bootstrap.Modal.getInstance(document.getElementById('inquiryModal'));
            modal.hide();
        } else {
            showToast(data.message || 'Error submitting inquiry', false);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('inquiry Submitted Successfully. ', true);
    })
    .finally(() => {
        submitButton.disabled = false;
    });
});
</script>

<?php include 'includes/footer.php'; ?> 